#include "display.h"
#include "xdg-shell.h"

#include <cstdint>

#include <string.h>

namespace ukuiwaylandclient
{

display::display()
{
    init();
}

display::~display()
{
    if (m_wl_registry) {
        delete m_wl_registry;
        m_wl_display = nullptr;
    }

    if (m_wl_display) {
        delete m_wl_display;
        m_wl_display = nullptr;
    }
}

void display::init()
{
    m_wl_display = new wl_display_t();
    m_wl_registry = m_wl_display->get_registry();
    m_wl_registry->on_global() = [this](uint32_t name, const char *interface, uint32_t version) {
        if (strcmp(interface, wl_compositor_t::interface()->name) == 0) {
            m_wl_compositor = new wl_compositor_t(m_wl_registry, name, std::min<uint32_t>(version, wl_compositor_t::interface()->version));
        } else if (strcmp(interface, xdg_wm_base_t::interface()->name) == 0) {
            m_xdg_wm_base = new xdg_wm_base_t(m_wl_registry, name, std::min<uint32_t>(version, xdg_wm_base_t::interface()->version));
        } else if (strcmp(interface, wl_shm_t::interface()->name) == 0) {
            m_wl_shm = new wl_shm_t(m_wl_registry, name, std::min<uint32_t>(version, wl_shm_t::interface()->version));
        }
    };
    m_wl_display->roundtrip();
}

bool display::isInitialized() const
{
    return m_wl_display != nullptr && m_wl_registry != nullptr;
}

void display::roundtrip()
{
    if (m_wl_display) {
        m_wl_display->roundtrip();
    }
}

int display::dispatch()
{
    if (m_wl_display) {
        return m_wl_display->dispatch();
    }
    return -1;
}

wl_compositor_t *display::compositor()
{
    return m_wl_compositor;
}

xdg_wm_base_t *display::xdgWmBase()
{
    return m_xdg_wm_base;
}

wl_shm_t *display::shm()
{
    return m_wl_shm;
}

} // namespace ukuiwaylandclient
